<?php

namespace app\admin\controller\work;

use app\common\controller\Backend;
use app\admin\model\WorkTemplateItem;
use app\admin\model\AuthGroupAccess;
use app\admin\model\WorkTemplateTime;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
/**
 * 浮动性工作模板管理管理
 *
 * @icon fa fa-circle-o
 */
class WorkTemplate extends Backend
{

    /**
     * WorkTemplate模型对象
     * @var \app\admin\model\WorkTemplate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WorkTemplate;
        $this->view->assign("type_arr", $this->model->type_arr);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where(['del_status'=>'1'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $time_info = WorkTemplateTime::where('id',$row->work_time_id)->find();
                if($time_info){
                    $row->start_time = $time_info['start_time'];
                    $row->end_time = $time_info['end_time'];
                }

                $row->visible(['id','name','work_time_id','type','start_time','end_time','week_str','create_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $validate = $this->validate($params, 'WorkTemplate.add');
                    if ($validate !== true) exception($validate);
                    $result = $this->model->allowField(true)->save($params);
                    if(!$result)exception('添加失败');
                    Db::commit();
                } catch (\Throwable $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $validate = $this->validate($params, 'WorkTemplate.edit');
                    if ($validate !== true) exception($validate);
                    $result = $row->allowField(true)->save($params);
                    if($result === false)exception('编辑失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    
    /**
     * 批量选择时间模版
     */
    public function select_time_temp($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $ids = explode(',',$ids);
                    foreach ($ids as $v){
                        $row = $this->model->get(['id' => $v]);
                        if (!$row)exception('ID：'.$v.'模版不存在');
                        $result = $row->allowField(true)->save($params);
                        if($result === false)exception('操作失败');
                    }
                    Db::commit();
                } catch (\Throwable $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $success_num = $error_num = 0;
        $msg = '';
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            if($maxColumnNumber != 2)exception('文档格式不正确');
            if($allRow < 1)exception('未读取到数据');
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                if(isset($values[0]) && !empty($values)){

                    switch ($values[0]){
                        case '分餐':
                            $type = 1;
                            break;
                        case '看班':
                            $type = 2;
                            break;
                        case '社团':
                            $type = 3;
                            break;
                        default:
                            $type = 0;
                            break;
                    }
                    if(!$type){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：类型不正确</br>';
                        continue;
                    }
                    $params = array(
                        'type' => $type,
                        'name' => $values[1]
                    );

                    $validate = $this->validate($params, 'WorkTemplate.add');
                    if ($validate !== true){
                        $error_num ++;
                        $msg .= $values[0].'：'.$validate.'</br>';
                        continue;
                    }
                    $result = $this->model->create($params);

                    if(!$result){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：导入失败</br>';
                        continue;
                    }else{
                        $success_num++;
                    }

                }
            }
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
        $msg = '导入失败：'.$error_num.'</br>'. $msg;
        $this->success('导入成功:'.$success_num.'</br>'.$msg);
    }

    /**
     * 选择模板列表
     */
    public function work_template_list()
    {
        $params = $this->request->param("");
        $name  = $this->request->param("name");
        $type = isset($params['custom']['type']) ? !empty($params['custom']['type']) ? $params['custom']['type'] : 0  : '';
        $where   = ['type' => $type,'del_status'=>'1'];
        $keyValue = $this->request->post("keyValue");
        if(!empty($keyValue))$where['id'] = $keyValue;
        if(!empty($name))$where['name'] = ['like','%'.$name.'%'];
        $work_template_list =$this->model->where($where)->field('id,name,work_time_id')->select();
        foreach ($work_template_list as &$v){
            $time_info = WorkTemplateTime::where('id',$v->work_time_id)->find();
            if($time_info){
                $v['name'] = $v['name'].' '.date('Y/m/d',strtotime($time_info['start_time'])).'-'.date('Y/m/d',strtotime($time_info['end_time']));
            }
        }
        $total  = count($work_template_list);
        return json(array('list'=>$work_template_list,'total'=>$total));
    }

    /**
     * 选择模板时间列表
     */
    public function work_template_time_list()
    {
        $params = $this->request->param("");
        $temp_id = isset($params['custom']['temp_id']) ? !empty($params['custom']['temp_id']) ? $params['custom']['temp_id'] : 0  : '';

        $work_template_info = $this->model->where(['id'=>$temp_id])->find();
        $work_id = 0;
        if($work_template_info)$work_id=$work_template_info['work_time_id'];
        $where   = ['work_id' => $work_id,'status'=>'1'];
        //添加年级组条件
//        $AuthGroupAccessInfo = AuthGroupAccess::where('uid',$this->auth->id)->find();
//        if($AuthGroupAccessInfo['group_id'] == 12){
//             $where[] = ['EXP',Db::raw("FIND_IN_SET(".$this->auth->grade_group.",grade_group)")];
//        }
        $keyValue = $this->request->post("keyValue");
        if(!empty($keyValue))$where['id'] = $keyValue;
        $work_template_time_list =WorkTemplateItem::where($where)->field('id,select_time as name')->select();
        foreach ($work_template_time_list as &$v){
            $v['name'] = date('Y/m/d',strtotime($v['name']));
        }
        $total  = count($work_template_time_list);
        return json(array('list'=>$work_template_time_list,'total'=>$total));
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = explode(',',$ids);
            try {
                $this->model->whereIn('id',$ids )->update(array('del_status'=>2));
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
